﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Authentication;
using System.Threading.Tasks;
using Ace;
using Ace.Application.Common;
using Ace.Application.Wiki;
using Ace.Entity.Wiki;
using Ace.IdStrategy;
using Ace.Web.Helpers;
using Ace.Web.Mvc;
using Ace.Web.Mvc.Authorization;
using Ace.Web.Mvc.Models;
using Chloe.Admin.Common;
using Chloe.Admin.Common.Tree;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace Chloe.Admin.Areas.Wiki.Controllers
{

    [Area(AreaNames.Wiki)]
    [Permission("wiki.users")]
    public class UsersController : WebController<IUsersService>
    {
        public IActionResult Index()
        {
            //IShopService SortService = this.CreateService<IShopService>();
            //List<SimpleShop2> ListShop = SortService.GetCacheList2();
            //ViewBag.ListShop = ListShop;

            IUsers_RoleService RoleService = this.CreateService<IUsers_RoleService>();
            List<Users_Role> ListRole = RoleService.GetList("");
            ViewBag.ListRole = ListRole;

            ViewBag.PartList = this.CreateService<IDistrictService>().GetList(1);

            return View();
        }

        [HttpGet]
        public ActionResult GetModels(Pagination pagination,int RoleID, string keyword="", int ST = -1)
        {
            int ShopID = 0;
            //if (this.CurrentSession.IsAdmin)
            //{

            //}
            //else
            //{
            //    ShopID = this.CurrentSession.ShopID;
            //}

            PagedData<Users> pagedData = this.Service.GetPageData(pagination, ShopID, RoleID, keyword, ST);
            return this.SuccessData(pagedData);
        }


        [Permission("wiki.users.delete")]
        [HttpPost]
        public ActionResult Delete(string id)
        { 
            this.Service.Delete(id);
            return this.SuccessMsg("删除成功");
        }

        [HttpGet]
        public ActionResult Add()
        {
             

            return View();
        }

 


        [Permission("wiki.users.edit")]
        [HttpPost]
        public ActionResult Edit(UpdateUsersInput modle)
        {   
            if(modle.ST==2)
            {
                //会员充值  通知用户
                string content = "您可以在商城操作购买和观看装机视频，有效期："+modle.RoleDate .ToString("yyyy-MM-dd")+ " .感谢您的支持，客服热线：027-83240615";
                string post_data = "{\"data\":{\"character_string1\":{\"value\":\"VIP信息通过审核\"},\"thing2\":{\"value\":\"" + content + "\"} },\"template_id\":\"Hz6CnqL0zI_frxezYEGAh13YG3YBtUXKSjrrC6aqUps\",\"touser\":\"" + modle.OpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                SendSubscribeMessage(modle.OpenID, post_data);
            }
            this.Service.Update(modle);
            return this.SuccessMsg("编辑成功");
        }


        public void SendSubscribeMessage(string OpenID, string post_data)
        {
            string key = "access_token";
            string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
            string access_token = string.Empty;

            MemoryCacheHelper mc = new MemoryCacheHelper();
            object obj = mc.Get(key);
            if (obj != null)
            {
                access_token = obj.ToString();
            }
            else
            {
                access_token = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(WxOpenAppId, WxOpenAppSecret);
                TimeSpan ts = TimeSpan.FromSeconds(7200);
                mc.Set(key, access_token, ts);
            }

            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;


            //string post_data = "{\"data\":{\"date1\":{\"value\":\"2010-6-26 16:20\"},\"name2\":{\"value\":\"Tom\"},\"phone_number3\":{\"value\":\"17796350280\"},\"phrase4\":{\"value\":\"加盟商\"} },\"template_id\":\"eA5s4VourWBu2Vql1gdRruqqeDtOm0uZD4pwpb4YqT4\",\"touser\":\"" + OpenID + "\",\"miniprogram_state\":\"developer\",\"page\":\"pages/ucenter/index/index\"}";

            string json = HttpPost(Url, post_data);

        }

        public string HttpPost(string uri, string jsontxt)
        {
            var handler = new HttpClientHandler();

            //X509Certificate2 certificate = GetMyX509Certificate(certName);

            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.SslProtocols = SslProtocols.Tls12;
            //handler.ClientCertificates.Add(certificate);
            var retData = string.Empty;
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                var content = new StringContent(jsontxt);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
                var response = httpClient.PostAsync(uri, content).Result;
                retData = response.Content.ReadAsStringAsync().Result;
            }
            return retData;
        }


        [Permission("wiki.users.add")]
        [HttpPost]
        public ActionResult Add(AddUsersInput modle)
        {
            modle.CreateDate = DateTime.Now;
            this.Service.Add(modle);
            return this.SuccessMsg("添加成功");
        }


        
        [HttpPost]
        public ActionResult RevisePassword(string userId, string newPassword)
        {
            if (userId.IsNullOrEmpty())
                return this.FailedMsg("userId 不能为空");

            //this.Service.RevisePassword(userId, newPassword);
            return this.SuccessMsg("重置密码成功");
        }


        public ActionResult GetDistrictList(int Pid)
        {
            if (Pid > 0)
            {
                List<District> list = this.CreateService<IDistrictService>().GetList(Pid);
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }

        }


        public IActionResult log()
        { 

            return View();
        }

        [HttpGet]
        public ActionResult GetLogModels(Pagination pagination, string time1 = "", string time2 = "", string keyword = "")
        {          

            PagedData<UsersPayInfo> pagedData = this.CreateService<IUsersPayService>().GetUsersPayInfoList(pagination,"", time1, time2, keyword);
            return this.SuccessData(pagedData);
        }

        public ActionResult GetList(string UserID)
        {
            List<UsersPayInfo> list = this.CreateService<IUsersPayService>().GetList(UserID);
            if(list.Count>0)
            {
                return this.SuccessData(list);
            }
            else
            {
                return this.SuccessMsg("没有充值记录");
            }
        }


        [HttpGet]
        public FileStreamResult Export()
        {
            //string sWebRootFolder = _hostingEnvironment.WebRootPath;
            string physicalFilePath = Directory.GetCurrentDirectory() + "\\" + Globals.Configuration["AppSettings:FileRootDir"]+"\\"+ Globals.Configuration["AppSettings:UploadXls"];

            string sFileName = @"充值记录"+DateTime.Now.ToString("yyyy-MM-dd")+".xlsx";
            //string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
            string FilePath = Path.Combine(physicalFilePath, sFileName);
            FileInfo file = new FileInfo(FilePath);
            if (file.Exists)
            {
                file.Delete();
                file = new FileInfo(FilePath);
            }

            List<UsersPayInfo> list = this.CreateService<IUsersPayService>().GetList("");

            using (ExcelPackage package = new ExcelPackage(file))
            {
                // add a new worksheet to the empty workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
                //First add the headers
                worksheet.Cells[1, 1].Value = "姓名";
                worksheet.Cells[1, 2].Value = "手机";
                worksheet.Cells[1, 3].Value = "充值金额";
                worksheet.Cells[1, 4].Value = "充值单号";
                worksheet.Cells[1, 5].Value = "充值日期";
                worksheet.Cells[1, 6].Value = "过期日期";

                int m = 0;
                //Add values
                for(var i=0;i<list.Count;i++)
                {
                    m = i + 2;
                    worksheet.Cells["A"+ m].Value = list[i].TrueName;
                    worksheet.Cells["B" + m].Value = list[i].Mobile.ToString();
                    worksheet.Cells["C" + m].Value = list[i].transaction_price.ToString();
                    worksheet.Cells["D" + m].Value = list[i].transaction_id.ToString();
                    worksheet.Cells["E" + m].Value = list[i].transaction_date.ToString("yyyy-MM-dd");
                    worksheet.Cells["F" + m].Value = list[i].expire_date.ToString("yyyy-MM-dd");
                }
                

                package.Save(); //Save the workbook.
            }
            //return File(FilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "充值记录.xlsx"); //welcome.txt是客户端保存的名字
            return File(new FileStream(FilePath, FileMode.Open), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "充值记录.xlsx");
        }



    }
}